<?php

namespace App\Http\Controllers\Wechat;

use App\Models\AnswerActivity;
use App\Models\AnswerActivityGift;
use App\Models\AnswerActivityLimitAddress;
use App\Models\AnswerActivityResource;
use App\Models\AnswerActivityUnit;
use App\Models\AnswerActivityUserAnswerRecord;
use App\Models\AnswerActivityUserPrize;
use App\Models\AnswerActivityUserStairsTotalNumber;
use App\Models\UserInfo;
use App\Validate\AnswerActivityValidate;
use App\Models\AnswerActivityUserUnit;
use App\Models\AnswerActivityWordResource;
use App\Models\OtherAccessNum;

/**
 * 活动管理
 */
class AnswerActivityController extends CommonController
{
    public $model = null;
    public $applyModel = null;
    public $validate = null;

    public function __construct()
    {
        parent::__construct();

        $this->model = new AnswerActivity();
        $this->validate = new AnswerActivityValidate();
    }


    /**
     * 扫码后获取活动信息
     * @param qr_id int 扫码后的token值
     * @param token 用户token
     * @param lon 经度
     * @param lat 纬度
     */
    public function scanActInfo()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('wx_scan_act_info')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        if (substr($this->request->qr_id, 0, 2) == 18) {
            //查询活动二维码
            $answerActivityModel = new AnswerActivity();
            $res = $answerActivityModel->getDetailByQrCode($this->request->qr_id);
            if (empty($res)) {
                return $this->returnApi(202, "请扫描活动二维码");
            }
            return $this->returnApi(200, "查询成功", true, ['act_id' => $res->id, 'act_type_id' => 1, 'is_attend' => false]);
        }
        //下面是处理单位问题
        $answerActivityUnitModel = new AnswerActivityUnit();
        $res = $answerActivityUnitModel->getDetailByQrCode($this->request->qr_id);
        if (empty($res)) {
            return $this->returnApi(202, "请扫描活动单位二维码");
        }
        //判断经纬度是否符合参赛要求
        if (empty($this->request->lon) || empty($this->request->lat)) {
            return $this->returnApi(211, "请开启手机定位功能");
        }
        $answerActivityLimitAddressModel = new AnswerActivityLimitAddress();
        $lon_lat_info = $answerActivityLimitAddressModel->checkLonLat($res->act_id, $this->request->lon, $this->request->lat);
        if ($lon_lat_info !== true) {
            return $this->returnApi(210, "您当前位置不在活动范围");
        }


        //判断用户是否选择了单位
        $answerActivityUserUnitModel = new AnswerActivityUserUnit();
        $is_select_unit = $answerActivityUserUnitModel->isSelectUnit($this->request->token, $res->act_id, null, 1);

        //判断此图书馆是否已删除
        if (!empty($is_select_unit['unit_id'])) {
            $unit_name = AnswerActivityUnit::where('id', $is_select_unit['unit_id'])->where('is_del', 1)->value('name');
        }
        if ($is_select_unit && !empty($unit_name)) {
            if ($res['id'] != $is_select_unit['unit_id']) {
                $activity_info = AnswerActivity::select('node', 'is_show_list')->where('id', $res->act_id)->first();
                //不是独立活动，并且列表不显示才返回 true
                if ($activity_info['node'] != 1 && $activity_info['is_show_list'] == 2) {
                    // $unit_name = AnswerActivityUnit::where('id', $is_select_unit['unit_id'])->value('name');
                    //表示之前已经参加过其他馆的活动
                    return $this->returnApi(200, "您已参加过“" . $unit_name . "”的活动，是否需要进入该馆？", true, ['act_id' => $res->act_id, 'act_type_id' => 1, 'is_attend' => true]);
                }
            }
            return $this->returnApi(200, "查询成功", true, ['act_id' => $res->act_id, 'act_type_id' => 1, 'is_attend' => false]);
        }
        //写入用户单位
        $result = $answerActivityUserUnitModel->addUserUnit($this->request->token, $res->act_id, $res->id);
        if ($result) {
            return $this->returnApi(200, "查询成功", true, ['act_id' => $res->act_id, 'act_type_id' => 1, 'is_attend' => false]);
        }
        return $this->returnApi(202, "扫码失败");
    }


    /**
     * 活动类型列表  (统一在这里配置)
     */
    public function typeList()
    {
        //添加阅读互动访问量（应用）
        $otherAccessNumModel = new OtherAccessNum();
        $otherAccessNumModel->add(6);

        $data = [
            ['id' => 1, 'name' => '竞答', 'intro' => '知识闯关，线上答题'],   //固定写法
            ['id' => 2, 'name' => '抽奖', 'intro' => '快来抽奖，赢精美礼品吧'],
            ['id' => 3, 'name' => '投票', 'intro' => '大赛投票，选出你的喜欢'],
            ['id' => 4, 'name' => '直播', 'intro' => '身临其境，观看活动现场'],
        ];
        return $this->returnApi(200, '获取成功', true, $data);
    }

    /**
     * 答题活动列表 （根据类型不同，调用不同的接口  act_type_id 为 1 调用此接口）
    //  * @param act_type_id   类型id
     * @param page int 页码
     * @param limit int 分页大小
     * @param keywords string 搜索关键词
     */
    public function lists()
    {
        //增加验证场景进行验证
        // if (!$this->validate->scene('wx_list')->check($this->request->all())) {
        //     return $this->returnApi(201,  $this->validate->getError());
        // }
        $page = $this->request->page ? intval($this->request->page) : 1;
        $limit = $this->request->limit ? intval($this->request->limit) : 10;
        $keywords = $this->request->keywords;

        $res = $this->model->lists(['id', 'img', 'title', 'start_time', 'end_time', 'answer_start_time', 'answer_end_time', 'browse_num'], $keywords, 1, null, null, null, null, null, null, null, $page, $limit);


        //增加行为分析
        $appInviteCodeBehaviorModel = new  \App\Models\AppInviteCodeBehavior();
        $appInviteCodeBehaviorModel->add(26);

        if ($res['total'] == 0 || !$res['data']) {
            return $this->returnApi(203, "暂无数据");
        }

        foreach ($res['data'] as $key => $val) {
            $res['data'][$key]['status'] = $this->model->getActListStatus($val);
            $res['data'][$key]['start_time'] = date('Y-m-d H:i', strtotime($val['start_time']));
            $res['data'][$key]['end_time'] = date('Y-m-d H:i', strtotime($val['end_time']));
        }
        $res = $this->disPageData($res);
        return $this->returnApi(200, "查询成功", true, $res);
    }

    /**
     * 获取答题活动详情 （根据类型不同，调用不同的接口  act_type_id 为 1 调用此接口）
     * @param id int id
     * @param token 用户token
     * 
     * @param lon 经度
     * @param lat 纬度
     */
    public function detail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('wx_detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        //判断经纬度是否符合参赛要求
        if (empty($this->request->lon) || empty($this->request->lat)) {
            return $this->returnApi(211, "请开启手机定位功能");
        }
        $answerActivityLimitAddressModel = new AnswerActivityLimitAddress();
        $lon_lat_info = $answerActivityLimitAddressModel->checkLonLat($this->request->id, $this->request->lon, $this->request->lat);
        if ($lon_lat_info !== true) {
            return $this->returnApi(210, "您当前位置不在活动范围");
        }

        $field = [
            'id', 'title', 'node', 'number', 'answer_number', 'rule_type', 'rule', 'share_number', 'answer_start_time',
            'answer_end_time', 'start_time', 'end_time', 'lottery_start_time', 'lottery_end_time', 'answer_rule', 'answer_time',
            'total_floor', 'is_loop', 'pattern', 'prize_form', 'is_show_list', 'is_show_small_rank', 'share_title', 'share_img', 'is_show_address',
            'technical_support', 'is_reset_data'
        ];
        $res = $this->model->detail($this->request->id, $field, 1);

        if (!$res) {
            return $this->returnApi(202, "活动不存在或已结束");
        }
        $res = $res->toArray();

        //是否自动重置数据
        if ($res['is_reset_data'] == 1 && $res['answer_start_time'] < date('Y-m-d H:i:s')) {
            $this->model->resetData($this->request->id, $res['answer_start_time']);
            $this->model->where('id', $this->request->id)->update(['is_reset_data' => 2]); //自动改为不可重置状态
        }

        //获取用户基本信息
        $userInfoModel = new UserInfo();
        $user_info = $userInfoModel->getWechatInfo($this->request->token);


        $res['user_info']['nickname'] = !empty($user_info) ? $user_info['nickname'] : '';
        $res['user_info']['head_img'] = !empty($user_info) ? $user_info['head_img'] : '';
        //获取现有抽奖钥匙个数
        $activityUserPrizeModel = new AnswerActivityUserPrize();
        $key_number = $activityUserPrizeModel->getUserPrizeNumber($res['id'], $this->request->token);
        $res['user_info']['key_number'] = empty($key_number) ? 0 : $key_number['number'] - $key_number['use_number'];
        //今日剩余答题次数
        $activityUserAnswerRecordModel = new AnswerActivityUserAnswerRecord();
        $res['user_info']['surplus_answer_number'] = $activityUserAnswerRecordModel->surplusAnswerNumber($this->request->token, $res['id'], $res['number'], $res['share_number']);

        //活动状态
        $res['status'] = $this->model->getActListStatus($res);

        //更新浏览量
        $this->model->updateBrowseNumber($this->request->id);

        //如果单位联盟，区域联盟不显示列表
        //   if ($res['is_show_list'] == 2 && $res['node'] != 1) {
        if ($res['node'] != 1) {
            //返回用户所属馆id
            $answerActivityUserUnitModel = new AnswerActivityUserUnit();
            $is_select_unit = $answerActivityUserUnitModel->isSelectUnit($this->request->token, $this->request->id, null, 1);

            $is_unit = null;
            //选择一个默认馆，赋值给用户
            $answerActivityUnitModel = new AnswerActivityUnit();
            if ($is_select_unit) {
                //判断此图书馆是否存在
                $is_exists = $answerActivityUnitModel->where('id', $is_select_unit->unit_id)->where('is_del', 1)->first();
                if ($is_exists) {
                    $is_unit = $is_select_unit->unit_id;
                }
            }
            if (empty($is_unit)) {
                $is_unit = $answerActivityUnitModel->getDefaultUnit($this->request->id);
                $result = $answerActivityUserUnitModel->addUserUnit($this->request->token, $this->request->id, $is_unit);
                if (empty($result)) {
                    return $this->returnApi(202, "网络错误，请重试");
                }
            }
            $res['user_unit_id'] = $is_unit;
        } else {
            $res['user_unit_id'] = null;
        }

        //判断是否需要地址
        $res['is_show_address'] = $res['is_show_address'] == 1 ? true : false;

        return $this->returnApi(200, "查询成功", true, $res);
    }
    /**
     * 爬楼梯模式获取当前楼层
     * @param id 活动id
     * @param unit_id 单位id 单位活动必须
     */
    public function getStairsFloor()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('wx_stairs_floor')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $res = $this->model->detail($this->request->id, ['id', 'total_floor', 'node', 'is_reset_data', 'answer_start_time'], 1);

        if (!$res) {
            return $this->returnApi(201, "参数传递错误");
        }
        $res = $res->toArray();

        //是否自动重置数据
        if ($res['is_reset_data'] == 1 && $res['answer_start_time'] < date('Y-m-d H:i:s')) {
            $this->model->resetData($this->request->id, $res['answer_start_time']);
            $this->model->where('id', $this->request->id)->update(['is_reset_data' => 2]); //自动改为不可重置状态
        }

        if ($res['node'] != 1 && empty($this->request->unit_id)) {
            return $this->returnApi(201, "单位id不能为空");
        }

        $unit_id = $this->request->unit_id;
        if ($res['node'] == 1) {
            $unit_id = 0;
        }

        //获取当前楼层
        $answerActivityUserStairsTotalNumberModel = new AnswerActivityUserStairsTotalNumber();
        $res['now_floor'] = $answerActivityUserStairsTotalNumberModel->where('user_guid', $this->request->token)
            ->where('act_id', $this->request->id)
            ->where(function ($query) use ($unit_id) {
                if ($unit_id) {
                    $query->where('unit_id', $unit_id);
                }
            })->value('correct_number');

        $res['now_floor'] = $res['now_floor'] ? $res['now_floor'] : 0; //1 表示刚开始

        if ($unit_id) {
            $res['unit_name'] = AnswerActivityUnit::where('id', $unit_id)->value('name');
        } else {
            //  $res['unit_name'] = config('other.unit_name');
            $res['unit_name'] = null;
        }
        return $this->returnApi(200, "查询成功", true, $res);
    }


    /**
     * 获取资源路径及颜色、文字等信息
     * @param id 活动id
     */
    public function getResourceInfo()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('wx_resource_info')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $answerActivityResourceModel = new AnswerActivityResource();
        $res = $answerActivityResourceModel->detail($this->request->id);
        if (empty($res)) {
            return $this->returnApi(202, "获取失败");
        }
        $res->act_title = $this->model->where('id', $this->request->id)->value('title');

        $res = $res->toArray();

        //获取文字资源
        $answerActivityWordResourceModel = new AnswerActivityWordResource();
        $data = $answerActivityWordResourceModel->getWordResource($this->request->id);
        $res['word'] = $data;

        return $this->returnApi(200, "查询成功", true, $res);
    }
}
